# MCP server for course schedule queries
from __future__ import annotations
import os
os.environ["COURSE_ACCESS_TOKEN"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzY0NDIxMzcxLCJpYXQiOjE3NjM4MTY1NzEsImp0aSI6ImVhMmIzZTJiM2FjMjQ2NWY5NzAyNTExY2FmYjQzYTczIiwidXNlcl9pZCI6M30.kwe24AecTCR69oYWQoAHuDv9hiAjI1yLacN7KkXqUfs"

import logging
import sys
from typing import Optional

import requests
from fastmcp import FastMCP

# Fix UTF-8 encoding for Windows console
if sys.platform == "win32":
    sys.stderr.reconfigure(encoding="utf-8")
    sys.stdout.reconfigure(encoding="utf-8")

logger = logging.getLogger("CourseSchedule")

# Default connection settings can be overridden by env vars at runtime
DEFAULT_BASE_URL = os.environ.get("COURSE_BASE_URL", "http://127.0.0.1:8000/api")
DEFAULT_ACCESS_TOKEN = os.environ.get("COURSE_ACCESS_TOKEN")

mcp = FastMCP("CourseSchedule")


def _build_headers(access_token: Optional[str]) -> dict:
    token = access_token or DEFAULT_ACCESS_TOKEN
    if token:
        return {"Authorization": f"Bearer {token}"}
    return {}


def _base_url(base_url: Optional[str]) -> str:
    return (base_url or DEFAULT_BASE_URL).rstrip("/")


@mcp.tool()
def get_day_schedule(
    student_id: str,
    flag: int = 1,
    base_url: Optional[str] = None,
    access_token: Optional[str] = None,
) -> dict:
    """Query today's or tomorrow's schedule text from the backend."""
    url = f"{_base_url(base_url)}/course/course_item/get_flag_day_course/"
    params = {"flag": flag, "student_id": student_id}
    headers = _build_headers(access_token)

    try:
        response = requests.get(url, params=params, headers=headers, timeout=15)
        content_type = response.headers.get("Content-Type", "")
        body = response.json() if "json" in content_type.lower() else response.text
        response.raise_for_status()
        logger.info("Fetched day schedule for %s via %s", student_id, response.url)
        return {
            "success": True,
            "status_code": response.status_code,
            "url": response.url,
            "data": body,
        }
    except requests.HTTPError as exc:
        return {
            "success": False,
            "status_code": response.status_code if "response" in locals() else None,
            "url": response.url if "response" in locals() else url,
            "error": str(exc),
            "body": body if "body" in locals() else None,
        }
    except Exception as exc:
        return {"success": False, "url": url, "error": str(exc)}


@mcp.tool()
def get_week_schedule(
    student_id: str,
    week: int = 1,
    base_url: Optional[str] = None,
    access_token: Optional[str] = None,
) -> dict:
    """Query this week's or next week's schedule text from the backend."""
    url = f"{_base_url(base_url)}/course/course_item/get_flag_week_course/"
    params = {"week": week, "student_id": student_id}
    headers = _build_headers(access_token)

    try:
        response = requests.get(url, params=params, headers=headers, timeout=15)
        content_type = response.headers.get("Content-Type", "")
        body = response.json() if "json" in content_type.lower() else response.text
        response.raise_for_status()
        logger.info("Fetched week schedule for %s via %s", student_id, response.url)
        return {
            "success": True,
            "status_code": response.status_code,
            "url": response.url,
            "data": body,
        }
    except requests.HTTPError as exc:
        return {
            "success": False,
            "status_code": response.status_code if "response" in locals() else None,
            "url": response.url if "response" in locals() else url,
            "error": str(exc),
            "body": body if "body" in locals() else None,
        }
    except Exception as exc:
        return {"success": False, "url": url, "error": str(exc)}


if __name__ == "__main__":
    mcp.run(transport="stdio")
